package com.ecp.commons.interceptor;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.ecp.commons.annotation.OpLog;

//import com.ecp.commons.annotation.OpLog;

public class ControllerInterceptor implements HandlerInterceptor {

	final private String[]	excludeList		= { "/pinzhiV2.0/error/", "/yyg/totalJoinamount.do", "/yyg/getBuyList.do" };
	final private String[]	logServerNames	= { "admin.pinzhi365.com", "192.168.1.4" };

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		String serverName = request.getServerName();
		boolean isLogServer = false;
		if (logServerNames != null) {
			for (String logServerName : logServerNames) {
				if (logServerName.equals(serverName)) {
					isLogServer = true;
					break;
				}
			}
		}
		if (!isLogServer) {
			return;
		}
		HttpSession session = null;
		try {
			session = request.getSession(false);
		} catch (Exception e) {
		}
		long startTime = (Long) request.getAttribute("_start_time");
		long duration = System.currentTimeMillis() - startTime;
		String uri = request.getRequestURI();
		//System.out.println("ControllerInterceptor.afterCompletion: " + uri);
		for (String exclude : excludeList) {
			if (uri.indexOf(exclude) >= 0) {
				return;
			}
		}

		boolean isJSP = uri.toUpperCase().endsWith(".JSP");

		HandlerMethod handlerMethod = (HandlerMethod) handler;
		OpLog opLog = handlerMethod.getMethodAnnotation(OpLog.class);
		boolean needLog = opLog == null || opLog.needlog();
		if ((isJSP || !needLog) && duration < 100) {
			return;
		}

		String paramStr = "";
		@SuppressWarnings("unchecked")
		Map<String, String[]> params = request.getParameterMap();
		for (Entry<String, String[]> entry : params.entrySet()) {
			String key = entry.getKey();
			String[] values = entry.getValue();
			if (key.equals("password")) {
				paramStr += "&" + key + "=***";
				continue;
			}
			for (String value : values) {
				paramStr += "&" + key + "=" + value;
			}
		}
		if (paramStr.length() > 0) {
			paramStr = paramStr.substring(1);
		}
		if (paramStr.length() > 1024) {
			paramStr = paramStr.substring(0, 1024);
		}

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String userAgent = request.getHeader("user-agent");
		if (StringUtils.isEmpty(userAgent) || userAgent.indexOf("Jakarta") >= 0) {
			return false;
		}
		if (userAgent.indexOf("sqlmap") >= 0) {
			response.getWriter().print("别试了，兄弟。");
			return false;
		}

		@SuppressWarnings("unchecked")
		Map<String, String[]> params = request.getParameterMap();
		for (String[] values : params.values()) {
			for (String value : values) {
				if (StringUtils.containsIgnoreCase(value, "UNION%20ALL")) {
					return false;
				} else if (StringUtils.containsIgnoreCase(value, "UNION ALL")) {
					return false;
				} else if (StringUtils.containsIgnoreCase(value, ")--")) {
					return false;
				}
			}
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		request.setAttribute("_operation_time", sdf.format(new Date()));
		request.setAttribute("_start_time", System.currentTimeMillis());
		/*		String uri = request.getRequestURI();
				if (uri.indexOf("error") < 0) {
					System.out.println("ControllerInterceptor.preHandle: " + uri);
				}
		*/return true;
	}

}
